package com.jxs.android.sxyw;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.sxyw.boot.SelfApplication;
import com.jxs.android.sxyw.data.NoticeInfo;
import com.jxs.android.sxyw.weiget.PopMsg;
import com.jxs.android.sxyw.weiget.TopBar;
import com.jxs.android.util.StartHelper;

/**
 * @Author Jiangxs
 * @Date 2011-8-4 下午11:35:38
 * @Des 3D旋转效果参见 PDF_p111
 */
public class Main extends AbstractActivity implements OnItemClickListener {

	private GridView appGridView = null;
	private Context context;
	private ProgressDialog progressDialog;

	/**
	 * @Des Activity 的界面入口
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.main);

		context = this;

		appGridView = (GridView) findViewById(R.id.main_app_gridview);
		appGridView.setNumColumns(4);
		appGridView.setAdapter(new AppAdpter(context));
		appGridView.setOnItemClickListener(this);
		progressDialog = ProgressDialog.show(this, "", "数据准备中，请稍候...", true);
		progressDialog.setCancelable(true);
		getLatestNotice(SelfApplication.getUserInfo().getTicket());
	}

	private void getLatestNotice(final String ticket) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String wsdl_url = SelfApplication.WSDL_URL;// wsdl
				String namespace = SelfApplication.WSDL_NAME_SPACE;// namespace
				String methodName = "getLatestNotice";// 要调用的方法名称
				SoapObject request = new SoapObject(namespace, methodName);
				request.addProperty("ticket", ticket);
				BuWebService webService = new BuWebService(wsdl_url, request);
				webService.setDoNet(false);
				webService.requestWSDL(new IWebService() {
					@Override
					public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
						SoapObject response = (SoapObject) envelope.getResponse();
						paser(response);
					}
				});
			}
		}).start();
	}

	private void paser(SoapObject soapObject) {
		String stauts = soapObject.getPropertySafelyAsString("status");
		SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
		String message = msgObjec.getPropertySafelyAsString("message");
		if ("-2".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
		} else if ("-1".equals(stauts)) {
			Message msg = new Message();
			msg.what = ERROR_MSG;
			msg.obj = message;
			handler.sendMessage(msg);
			StartHelper.startActivity(Login.class);
			this.finish();
		} else if ("0".equals(stauts)) {
			SoapObject taskBeanObject = (SoapObject) soapObject.getProperty("retMsg");
			if (null != taskBeanObject) {
				NoticeInfo noticeListInfo = new NoticeInfo();
				noticeListInfo.setNotice_id(taskBeanObject.getPropertySafelyAsString("notice_id"));
				noticeListInfo.setNotice_title(taskBeanObject.getPropertySafelyAsString("notice_title"));
				noticeListInfo.setNotice_date(taskBeanObject.getPropertySafelyAsString("notice_date"));
				noticeListInfo.setNotice_content(taskBeanObject.getPropertySafelyAsString("notice_content"));
				Message msg = new Message();
				msg.what = SHOW_ALERT;
				msg.obj = noticeListInfo;
				handler.sendMessage(msg);
			} else {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}
		}
	}

	private void show(NoticeInfo info, final Intent intent) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("系统公告");
		builder.setMessage(info.getNotice_title()).setCancelable(false).setPositiveButton("查看", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				context.startActivity(intent);
				dialog.cancel();
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	private int SHOW_ALERT = 0x331;
	private int ERROR_MSG = 0x332;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.cancel();
			}
			if (msg.what == SHOW_ALERT) {
				if (null != msg.obj) {
					NoticeInfo info = (NoticeInfo) msg.obj;
					Intent intent = new Intent(context, NoticeDetail.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("noticeInfo", info);
					intent.putExtras(bundle);
					show(info, intent);
				}
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			}
		}
	};

	@Override
	public void topBarLogic(TopBar topBar) {
		topBar.hindAllBtn();
		topBar.setTitle(R.string.app_name);
	}

	/**
	 * @Des 点击中间的图片的时候处理事件
	 */

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

		switch (position) {
		case 0: {// 隐患上报
			StartHelper.startActivity(Inspection.class);
			break;
		}
		case 1: {// 隐患上报
			StartHelper.startActivity(DangerList.class);
			break;
		}
		case 2: {// 任务工单
			StartHelper.startActivity(CaseTaskList.class);
			break;
		}
		case 3: {// 告警工单
			StartHelper.startActivity(CaseAlarmList.class);
			break;
		}
		case 4: {// EOMS告警
			StartHelper.startActivity(EomsAlarmList.class);
			break;
		}
		case 5: {// EOMS停电
			StartHelper.startActivity(EomsPowerList.class);
			break;
		}
		case 6: {// 公告
			StartHelper.startActivity(NoticeList.class);
			break;
		}
		default: {// 其他
			PopMsg.show("建设中...请稍后..");
			testFileUpload();
			break;
		}
		}
	}

	/**
	 * @Des this method used to test update picture file used httpCilent
	 */
	void testFileUpload() {
		ArrayList<String> files = new ArrayList<String>();
		files.add("1346766864252.jpg");
		files.add("1346766880759.jpg");
		files.add("1346766917057.jpg");
		files.add("1346766927869.jpg");
		files.add("1346766940033.jpg");

		Intent intent = new Intent(this, UploadPic.class);
		Bundle bundle = new Bundle();
		bundle.putStringArrayList("fileNames", files);
		bundle.putString("danger_id", "1646");
		bundle.putString("upload_url", "http://192.168.43.24:8080/mmsws/MobileAction.do?method=uploadFile");
		bundle.putString("ticket", SelfApplication.getUserInfo().getTicket());
		intent.putExtras(bundle);
		startActivityForResult(intent, 11);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuItem item = menu.add(0, 401, 402, "退出");// 可以通过点击这个菜单项来改变tv1的值这样(变成M)就可以测试了
		item.setIcon(R.drawable.menu_exit);
		item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				processMenuClose(context);
				return false;
			}
		});
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			processMenuClose(context);
		}
		return false;
	}

	/**
	 * @Des 处理关闭
	 * @param context
	 */
	private void processMenuClose(Context context) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setMessage("确认退出吗？");
		builder.setTitle("提示");
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Main.this.finish();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	private class AppAdpter extends BaseAdapter {

		List<AppInfo> appInfos = getAppInfos();

		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public AppAdpter(Context context) {
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return appInfos.size();
		}

		@Override
		public AppInfo getItem(int position) {
			return appInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			AppInfo appInfo = appInfos.get(position);

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.img_tv_item, null);
				holder = new ViewHolder();
				holder.icon_iv = (ImageView) convertView.findViewById(R.id.gridView_ImageViewItem);
				holder.name_tv = (TextView) convertView.findViewById(R.id.gridView_TextViweItem);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.icon_iv.setImageResource(appInfo.getImgResid());
			holder.name_tv.setText(appInfo.getTextResId());
			holder.name_tv.setTextColor(Color.rgb(255, 255, 255));
			return convertView;
		}

		private class ViewHolder {
			ImageView icon_iv;
			TextView name_tv;
		}

	}

	/**
	 * @Des 这里是图片和文字的集合
	 * @return
	 */
	private List<AppInfo> getAppInfos() {

		List<AppInfo> appInfos = new ArrayList<Main.AppInfo>();

		// @0代维巡检
		AppInfo map = new AppInfo(R.drawable.daiweixunjian, R.string.main_xunjian_label);
		appInfos.add(map);
		// @1隐患上报
		map = new AppInfo(R.drawable.yinhuanshangbao, R.string.main_yinhuan_label);
		appInfos.add(map);
		// @2 任务工单
		map = new AppInfo(R.drawable.icon_case_task, R.string.main_case_task_label);
		appInfos.add(map);
		// @3告警工单
		map = new AppInfo(R.drawable.icon_case_alarm, R.string.main_case_alarm_label);
		appInfos.add(map);
		// @4//EOMS告警
		map = new AppInfo(R.drawable.eoms_fangyu, R.string.main_eoms_fangyu_label);
		appInfos.add(map);
		// @5EOMS听发电
		map = new AppInfo(R.drawable.eoms_tingdian, R.string.main_eoms_tingdian_label);
		appInfos.add(map);
		// @6
		map = new AppInfo(R.drawable.xitonggonggao, R.string.main_gonggao_label);
		appInfos.add(map);

		return appInfos;
	}

	class AppInfo {
		int imgResid;
		int textResId;

		public int getImgResid() {
			return imgResid;
		}

		public void setImgResid(int imgResid) {
			this.imgResid = imgResid;
		}

		public int getTextResId() {
			return textResId;
		}

		public void setTextResId(int textResId) {
			this.textResId = textResId;
		}

		public AppInfo(int imgResid, int textResId) {
			this.imgResid = imgResid;
			this.textResId = textResId;
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

}